/*

	tools23d - tools for converting images to 3D formats.
    Copyright (C) 2014  Dave Gorst

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

*/
#include <stdio.h>
#include <glob.h>
#include <limits.h>
#include <time.h>
#include <libgen.h>
#include <sys/stat.h>

#include "tools23d.h"
#include "glob-all.h"

#ifdef __GNUC__
	#define GLOB_OPTIONS GLOB_TILDE
#else
	#define GLOB_OPTIONS NULL
#endif

static glob_t globbuf;

/**
Populate globule according to file pattern (POSIX version).

@param  globule Index of globule to populate.
@param  filename_pattern    Filename pattern with which to do so.
@return Number of entries added.
*/

unsigned int T3D_PopulateGlob (unsigned int globule, char * filename_pattern)
{
   	int counter;

	char write_file [MAX_PATH];

	char * filepath_base;

	struct stat status;

	glob (filename_pattern, GLOB_OPTIONS, NULL, &globbuf);

    filepath_base = dirname (filename_pattern);

	for(counter = 0; counter < globbuf.gl_pathc; ++counter )
	{
		(void) sprintf (write_file, "%s/%s", filepath_base, basename (globbuf.gl_pathv[counter]));
        if (!stat (write_file, &status))
            T3D_AppendEntry ( globule, write_file, status.st_ctime );
	}

	globfree (&globbuf);

	return counter;

}
